package master;

import java.util.Arrays;

/**
 * @author chenyw
 * @date 2022/7/23 12:57
 */
public class M16threeSumClosest {
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        int min = Integer.MAX_VALUE;
        int res = 0;
        Arrays.sort(nums);
        for (int i = 0; i < n - 2; i++) {
            int t = target - nums[i];
            int second = i + 1;
            int third = n - 1;
            while (second < third) {
                int sum = nums[second] + nums[third];
                int tmp;
                if (t < 0 && sum >= 0) {
                    tmp = sum - t;
                } else if (t >= 0 && sum < 0) {
                    tmp = t - sum;
                } else {
                    tmp = Math.abs(t - sum);
                }
                if (tmp < min) {
                    min = tmp;
                    res = nums[i] + sum;
                }
                if (sum == t) {
                    return res;
                }
                if (sum > t) {
                    third--;
                } else {
                    second++;
                }
            }
        }
        return res;
    }
}
